# 导入DataApi
from jaqs.data import DataApi
import math
import datetime
# 初始化api
api = DataApi('tcp://data.quantos.org:8910')
# 获取用户名和密码
import os
user  = os.environ.get("QUANTOS_USER")
token = os.environ.get("QUANTOS_TOKEN")
# user = '15032264838'
# token = 'eyJhbGciOiJIUzI1NiJ9.eyJjcmVhdGVfdGltZSI6IjE1ODE0ODA4NjQ3NDgiLCJpc3MiOiJhdXRoMCIsImlkIjoiMTUwMzIyNjQ4MzgifQ.9csfAM7DuHqhFv6P0M026dvOSXfEdNj5tJT-DT0dr80'

# 登录
info, msg = api.login(user, token)
print(info, msg)
# 获得HS300指数20180322的成份股
def get_pe_ttm(date):
    pe=[]
    df, msg = api.query(
        view = 'lb.indexCons',
        filter="index_code=000300.SH&start_date="+date+"&end_date="+date
    )
    stock_list=df["symbol"]
    symbols = ",".join(df['symbol'])
    #print(stock_list)
    # 获得HS300成份股的日估值数据
    df_data, msg = api.query(
        view = 'lb.secDailyIndicator',
        filter="start_date="+date+"&end_date="+date+"&symbol="+symbols,
        fields='total_mv,float_mv,pe_ttm,pb,trade_date'
    )
    df_data.set_index('symbol', inplace=True)
    #print(df_data)
    for k in stock_list:
        if(k!=''):
            try:
                pe.append(float(df_data.ix[str(k)]['pe_ttm']))
            except Exception as e:
                pass
        if(k==''):
            pe.append(-1.0)
    return pe,stock_list
def price(date,code):
    df_zsyh, msg = api.daily(
        symbol=code,
        start_date='2008-01-01',
        end_date='2018-12-31',
        fields='open,high,low,close',
    )
    for i in range(0,len(df_zsyh)):
        if(date==str(df_zsyh.ix[i]['trade_date'])):
            return float(df_zsyh.ix[i]['close'])
    return
startdate='20150519'
enddate='20180322'
pe,list_c=get_pe_ttm(startdate)
print('不复权')
for i in range(0,300):
    #print(pe[i],list_c[i])
    if(list_c[i]!=""):
        try:
            oldprice=float(price(startdate,list_c[i]))
            newprice=float(price(enddate,list_c[i]))
            r=(math.pow(2,(1/pe[i]))-1)*100
            if(r>=8):
                if(newprice>=oldprice):
                    print('股票代码',list_c[i],'开始日期',startdate,'结束日期',enddate)
                    print('原价：',oldprice,'现价',newprice,'PE-TTM',pe[i],'收益率',str(r)+'%')
        except Exception as e:
            pass
print('数据输出完毕')
